package com.xvyy.tingshu.account.receiver;


import com.alibaba.fastjson.JSONObject;
import com.xvyy.tingshu.account.service.MqOpsService;
import com.xvyy.tingshu.common.execption.TsException;
import com.xvyy.tingshu.common.rabbit.constant.MqConst;
import com.xvyy.tingshu.common.rabbit.service.RabbitService;
import com.xvyy.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * ClassName: UserAccountReceiver
 * Package: com.xvyy.tingshu.account.consumer
 *
 * @Description:
 * @Author: xvyy
 * @Create: 2025/1/13 - 20:14
 * @Version: v1.0
 */
@Component
@Slf4j
public class UserAccountReceiver {

    @Autowired
    private MqOpsService mqOpsService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RabbitService rabbitService;


    /**
     * 用户注册的消息消费者
     * @param content
     * @param message
     * @param channel
     *
     * @param content
     * @param message
     * @param channel
     */
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(name = MqConst.EXCHANGE_ACCOUNT),
            key = MqConst.ROUTING_USER_REGISTER,
            value = @Queue(name = MqConst.QUEUE_USER_REGISTER, durable = "true")))
    @SneakyThrows
    public void listenUserAccountInit(String content, Message message, Channel channel) {
        // 1. 获取消息，进行判断
        if (StringUtils.isEmpty(content)) {
            return;
        }
        // 2. 消费消息
        mqOpsService.userAccountInit(content);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        // 3. 手动确认消息
        channel.basicAck(deliveryTag, false);
    }

    /**
     * 解锁用户账户的消息消费者
     * @param content
     * @param message
     * @param channel
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ACCOUNT_UNLOCK, durable = "true", exclusive = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ACCOUNT),
            key = MqConst.ROUTING_ACCOUNT_UNLOCK))
    @SneakyThrows
    public void listenUnlock(String content, Message message, Channel channel) {
        // 1. 获取消息，进行判断
        if (StringUtils.isEmpty(content)) {
            return;
        }
        // 2. 消息转换
        TrackStatMqVo trackStatMqVo = JSONObject.parseObject(content, TrackStatMqVo.class);
        // 3. 消费消息
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            // 3.1 扣减用户账户余额操作
            mqOpsService.unlock(content);
            // 4. 发消息给本地消息表
            rabbitService.sendMessage(MqConst.EXCHANGE_LOCAL_MSG, MqConst.ROUTING_LOCAL_MSG, content);
            // 5. 手动应答
            channel.basicAck(deliveryTag, false);
        } catch (TsException e) {
            // 6. 重试 消息继续能够被消费者消费
            String retryMsgKey = "retry:msg:" + trackStatMqVo.getBusinessNo();
            Long increment = stringRedisTemplate.opsForValue().increment(retryMsgKey);
            if (increment >= 1) {
                log.error("消息重试了{}次，异常原因：{}，请人工排查", increment, e.getMessage());
                channel.basicNack(deliveryTag, false, false);  // 删除掉
            } else {
                log.error("消息重试了{}次", increment);
                channel.basicNack(deliveryTag, false, true);
            }
        } catch (Exception e) {
            log.error("手动应答期间，网络出现了抖动，但是业务已经被成功执行过，消息直接丢掉");
            log.error("异常原因：{}", e.getMessage());
            channel.basicNack(deliveryTag, false, false);
        }
    }

    /**
     * 扣减用户账户余额的消费者
     * @param content
     * @param message
     * @param channel
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ACCOUNT_MINUS, durable = "true", exclusive = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ACCOUNT),
            key = MqConst.ROUTING_ACCOUNT_MINUS))
    @SneakyThrows
    public void listenMinus(String content, Message message, Channel channel) {
        // 1. 获取消息，进行判断
        if (StringUtils.isEmpty(content)) {
            return;
        }
        // 2. 消费消息
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            // 3. 扣减用户账户余额操作
            mqOpsService.minus(content);
            // 4. 发消息给本地消息表
            rabbitService.sendMessage(MqConst.EXCHANGE_LOCAL_MSG, MqConst.ROUTING_LOCAL_MSG, content);
            // 5. 手动应答
            channel.basicAck(deliveryTag, false);
        } catch (TsException e) {
            // 6. 重试 消息继续能够被消费者消费
            String retryMsgKey = "retry:msg:" + content;
            Long increment = stringRedisTemplate.opsForValue().increment(retryMsgKey);
            if (increment >= 3) {
                log.error("消息重试了{}次，异常原因：{}，请人工排查", increment, e.getMessage());
                channel.basicNack(deliveryTag, false, false);  // 删除掉
            } else {
                log.error("消息重试了{}次", increment);
                channel.basicNack(deliveryTag, false, true);
            }
        } catch (Exception e) {
            log.error("手动应答期间，网络出现了抖动，但是业务已经被成功执行过，消息直接丢掉");
            log.error("异常原因：{}", e.getMessage());
            channel.basicNack(deliveryTag, false, false);
        }
    }


}
